package com.stylefeng.guns.modular.pay.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.stylefeng.guns.core.util.HttpUtils;
import com.stylefeng.guns.core.util.JsonUtils;
import com.stylefeng.guns.core.util.MD5Utils;
import com.stylefeng.guns.core.util.ObjectUtils;
import com.stylefeng.guns.modular.pay.dao.MchRegMapper;
import com.stylefeng.guns.modular.pay.dto.MchRegACDTO;
import com.stylefeng.guns.modular.pay.dto.MchRegDTO;
import com.stylefeng.guns.modular.pay.dto.MchRegParams;
import com.stylefeng.guns.modular.pay.exception.BusException;
import com.stylefeng.guns.modular.pay.exception.ResultEnum;
import com.stylefeng.guns.modular.pay.model.MchReg;
import com.stylefeng.guns.modular.pay.payment.jft.common.JftConfigure;
import com.stylefeng.guns.modular.pay.payment.jft.core.AESUtil;
import com.stylefeng.guns.modular.pay.payment.jft.core.MD5Util;
import com.stylefeng.guns.modular.pay.service.IMchRegService;

/**
 * <p>
 * 佳付通商户注册 服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2018-08-17
 */
@Service
public class MchRegServiceImpl extends ServiceImpl<MchRegMapper, MchReg> implements IMchRegService {
    private final static Logger logger = LoggerFactory.getLogger(MchRegServiceImpl.class);

	@Autowired
	private MchRegMapper mchRegMapper;
	
	@Override
	public List<MchReg> list(Page<MchReg> page,  MchRegParams params) {
		return mchRegMapper.list(page,params);
	}

	@Override
	public MchReg findByChMerCode(String chMerCode) {
		MchReg reg = new MchReg();
		reg.setChMerCode(chMerCode);
		return mchRegMapper.selectOne(reg);
	}

	@Override
	public MchReg findByMchNoAndMerCode(String mchNo, String merCode) {
		MchReg reg = new MchReg();
		reg.setMchNo(mchNo);
		reg.setMerCode(merCode);
		return mchRegMapper.selectOne(reg);
	}

	@Override
	public void update(Integer id, int status, String resCode, String resMsg) {
		MchReg reg = new MchReg();
		reg.setId(id);
		reg.setStatus(status);
		reg.setResCode(resCode);
		reg.setResMsg(resMsg);
		mchRegMapper.updateById(reg);
	}

	@Override
	public void update(Integer id, int status, String chMerCode, String resCode, String resMsg) {
		MchReg reg = new MchReg();
		reg.setId(id);
		reg.setStatus(status);
		reg.setResCode(resCode);
		reg.setResMsg(resMsg);
		reg.setChMerCode(chMerCode);
		mchRegMapper.updateById(reg);
	}

	@Override
	public MchRegACDTO getExportData(MchRegParams param) {
		MchRegACDTO acdto = new MchRegACDTO();
		List<MchReg> list =mchRegMapper.getExportData(param);
		List<MchRegDTO> details = new ArrayList<MchRegDTO>();
		for(MchReg mch:list){
			MchRegDTO dto =new MchRegDTO();
			dto.setAccountName(mch.getAccountName());
			dto.setAccountNo(mch.getAccountNo());
			dto.setBankCode(mch.getBankCode());
			dto.setBankName(mch.getBankName());
			dto.setChMerCode(mch.getChMerCode());
			dto.setCityCode(mch.getCityCode());
			dto.setIdcard(mch.getIdCard());
			dto.setMchNo(mch.getMchNo());
			dto.setMerAddress(mch.getMerAddress());
			dto.setMerCode(mch.getMerCode());
			dto.setMerName(mch.getMerName());
			dto.setMobile(mch.getMobile());
			dto.setOpenCity(mch.getOpenCity());
			dto.setOpenProvince(mch.getOpenProvince());
			dto.setPlatMerCode(mch.getPlatMerCode());
			dto.setProvinceCode(mch.getProvinceCode());
			dto.setReservedMobile(mch.getReservedMobile());
			if(0==mch.getStatus()){
				dto.setStatus("未注册");
			}else if(1==mch.getStatus()){
				dto.setStatus("注册成功");
			}else if(2==mch.getStatus()){
				dto.setStatus("注册失败");
			}
			dto.setSubBankCode(mch.getSubBankCode());
			details.add(dto);
		}
		acdto.setDetail(details);
		return acdto;
	}

	
	@Override
	public void reg(MchReg req) {
		//请求参数封装
		
		Map<String,String> mchMap = new HashMap<String,String>();
		mchMap.put("verCode", "1001");
		mchMap.put("merCode", req.getMerCode());
		mchMap.put("merName", req.getMerName());
		mchMap.put("realName", req.getRealName());
		if(!Strings.isNullOrEmpty(req.getProvinceCode())){
			mchMap.put("provinceCode", req.getProvinceCode());
		}
		if(!Strings.isNullOrEmpty(req.getCityCode())){
			mchMap.put("cityCode", req.getCityCode());
		}
		if(!Strings.isNullOrEmpty(req.getMerAddress())){
			mchMap.put("merAddress", req.getMerAddress());	
		}
		mchMap.put("idCard", req.getIdCard());
		mchMap.put("mobile", req.getMobile());
		mchMap.put("accountName", req.getAccountName());
		mchMap.put("accountNo", req.getAccountNo());
		mchMap.put("reservedMobile", req.getReservedMobile());
		if(!Strings.isNullOrEmpty(req.getBankName())){
			mchMap.put("bankName", req.getBankName());
		}
		if(!Strings.isNullOrEmpty(req.getBankCode())){
			mchMap.put("bankCode", req.getBankCode());
		}
		if(!Strings.isNullOrEmpty(req.getOpenProvince())){
			mchMap.put("openProvince", req.getOpenProvince());
		}
		if(!Strings.isNullOrEmpty(req.getOpenCity())){
			mchMap.put("openCity", req.getOpenCity());
		}
		mchMap.put("subBankCode", req.getSubBankCode());
		String linkString = MD5Utils.createLinkString(mchMap);
		String sign = MD5Util.encrypt(linkString+"&md5key="+JftConfigure.MD5_KEY, "UTF-8");
		byte[] encrypt;
		try {
			encrypt = AESUtil.encryptAES(JsonUtils.mapToJson(mchMap).getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
		} catch (Exception e1) {
			throw new BusException(ResultEnum.UNKONW_EXCEPTION);
		}

		//请求参数封装
		Map<String,String> dataMap = new HashMap<String,String>();
		dataMap.put("orgCode", JftConfigure.ORG_CODE);
		try {
			dataMap.put("encryptData", new String(encrypt,"UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		dataMap.put("signData", sign);

		String resStr = "";
		try {
			resStr = HttpUtils.post(JftConfigure.BASE_URL+"/fusionPosp/interface/memberReg", dataMap);
		} catch (Exception e) {
			throw new BusException(ResultEnum.UNKONW_EXCEPTION);	
		}
		logger.info("resStr="+resStr);
		if(Strings.isNullOrEmpty(resStr)){
			throw new BusException("channel.unkonw.exception","未知异常");
		}
		JSONObject jsonObject = JSON.parseObject(resStr);
		if(jsonObject.containsKey("resCode")&& !"0000".equals(jsonObject.getString("resCode"))){
			String resCode = jsonObject.getString("resCode");
			String resMsg = jsonObject.getString("resMsg");
			update(req.getId(),2,resCode,resMsg);
			logger.info("渠道响应：resCode={}|resMsg={}",resCode,resMsg);
			throw new BusException(ResultEnum.CHANNEL_RESPONSE_ERROR, resMsg);
		}
		JSONObject resObject = null;
		String encryptData = jsonObject.getString("encryptData");
		try {
			byte[] resDate = AESUtil.decryptAES(encryptData.getBytes(), JftConfigure.AES_KEY.getBytes(), true, "UTF-8");
			resObject = JSON.parseObject(new String(resDate,"UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("resObject="+resObject.toJSONString());
		String resCode = resObject.getString("resCode");
		String resMsg = resObject.getString("resMsg");
		if("0000".equals(resCode)){
			String chMerCode = resObject.getString("chMerCode");
			update(req.getId(),1,chMerCode,resCode,resMsg);
		}else{
			update(req.getId(),2,resCode,resMsg);
		}	
	}

	@Override
	public MchReg findByMchNo(String memberNo) {
		MchReg reg = new MchReg();
		reg.setMchNo(memberNo);
		return mchRegMapper.selectOne(reg);
	}

}
